const Koa = require('koa');
const app = new Koa();
const serve = require('koa-static');

app.use(serve(__dirname + '/dist'));


var fs = require('fs');
var path = require('path')
var sourceMap = require("source-map");

const rawSourceMap = {
  version: 3,
  file: "min.js",
  names: ["bar", "baz", "n"],
  sources: ["one.js", "two.js"],
  sourceRoot: "http://example.com/www/js/",
  mappings: "CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA"
};

app.use(async ctx => {
  let sourcemapFilePath = path.join(__dirname, './dist/js/test_vue.js.map');
  let sourceMapContent = fs.readFileSync(sourcemapFilePath, 'utf-8');
  let fileObj = JSON.parse(sourceMapContent);
  // fileObj.mappings = "CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA";
  // const whatever = await sourceMap.SourceMapConsumer.with(fileObj, null, consumer => {
  //   console.log(consumer.sources);
  //   for(let i = 0; i < 100; i++) {
  //     console.log(
  //       i,
  //       consumer.originalPositionFor({
  //         line: 1,
  //         column: 0 + i
  //       })
  //     );
  //   }
  // });
  // ctx.body = 'shit';
  // ctx.body = rawSourceMap; // 'Hello World';
  var rawSourceMap = fs.readFileSync(sourcemapFilePath).toString();
    // 通过sourceMap库转换为sourceMapConsumer对象
    var consumer = await new sourceMap.SourceMapConsumer(rawSourceMap);
    // 传入要查找的行列数，查找到压缩前的源文件及行列数
    var sm = consumer.originalPositionFor({
        line: 1,  // 压缩后的行数
        column: 88  // 压缩后的列数
      });
    // 压缩前的所有源文件列表
    var sources = consumer.sources;
    // 根据查到的source，到源文件列表中查找索引位置
    var smIndex = sources.indexOf(sm.source);
    // 到源码列表中查到源代码
    var smContent = consumer.sourcesContent[smIndex];
    // 将源代码串按"行结束标记"拆分为数组形式
    const rawLines = smContent.split(/\r?\n/g);
    // 输出源码行，因为数组索引从0开始，故行数需要-1
    console.log(rawLines[sm.line - 1]);
});



app.listen(3000);